package com.story.framework.core.utils.Hot100.java;


import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Xiaohei
 * @CreateTime: 2022/2/15 19:16
 */
public class LongestSubstringWithoutRepeatingCharacters {

    public static void main(String[] args) {
        int i = lengthOfLongestSubstring("au");
        System.out.println(i);
    }

    /**
     * 执行用时：6 ms, 在所有 Java 提交中击败了61.50%的用户
     * 内存消耗：41.7 MB, 在所有 Java 提交中击败了6.05%的用户
     *
     * @param s s
     * @return length
     */
    public static int lengthOfLongestSubstring(String s) {
        int maxLength = 0;
        int rp = 0;
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (i != 0) {
                set.remove(s.charAt(i-1));
            }
            while (rp < s.length() && !set.contains(s.charAt(rp))) {
                set.add(s.charAt(rp));
                rp++;
            }
            maxLength = Math.max(maxLength, rp - i);
        }
        return maxLength;
    }
}
